"""
九两三，一种基于 Rime，将 26 键合并为 9 键的，双拼三码输入方案
"""

from typing import Optional

from aux_code import *
from dict import RimeDict
from unipy import Unipy

_singleDict8105: Optional[RimeDict] = None
_singleDictExt: Optional[RimeDict] = None
_temp_dir = '../out/rime923'
_aux_file = '../out/rime923/single_aux.txt'
_version = '2309.1'
_code_to_digital = {
    'e': '1',
    'v': '1',
    'i': '2',
    'u': '3',
    'o': '4',
    'a': '5',
}


def build():
    global _code_to_digital
    print('923方案')
    empty_dir(_temp_dir)
    _load_single_dict()
    _make_single_pinyin()
    _make_phrase_pinyin_base()
    build_single_aux(AUX_JD6_SRC, _aux_file, _code_to_digital)
    unipy = Unipy(_aux_file)
    unipy.writeTableDict()
    unipy.writeScriptDict()
    _write_schema()
    _bundle()


def _load_single_dict():
    global _singleDict8105
    global _singleDictExt
    _singleDict8105 = RimeDict(SINGLE_PINYIN_8105_SRC)
    _singleDictExt = RimeDict(SINGLE_PINYIN_EXT_SRC)
    _singleDict8105.load(skip_head=True)
    _singleDictExt.load(skip_head=True)


def _make_single_pinyin():
    global _singleDict8105
    global _singleDictExt
    if is_file_exists(DICT_PINYIN_SINGLE_LITE):
        return

    out = create_utf8_file(DICT_PINYIN_SINGLE_LITE)
    out.write('# 简体中文单字拼音词库-精简版\n')
    out.write('# 未知读音用 X 表示\n')
    with open_file_as_utf8(SINGLE_LITE_SET) as f:
        for line in f:
            if line.startswith('#'):
                continue
            segments = line.split('\t')
            text = segments[0].strip()
            if _singleDict8105.hasText(text):
                for item in _singleDict8105.items:
                    if item.text == text:
                        out.write('{}\n'.format(item))
            elif _singleDictExt.hasText(text):
                for item in _singleDictExt.items:
                    if item.text == text:
                        out.write('{}\n'.format(item))
            else:
                print('{} not found!'.format(text))
                out.write('# {}\t{}\t{}\n'.format(text, 'X', 0))
            out.flush()
    out.close()


def _make_phrase_pinyin_base():
    if is_file_exists(DICT_PINYIN_PHRASE_BASE):
        return

    baseDict = RimeDict(PHRASE_PINYIN_BASE_SRC)
    baseDict.load(skip_head=True)
    items = []
    items.extend(baseDict.items)
    items.sort(key=lambda x: (len(x.text), x.code, -x.weight))
    with create_utf8_file(DICT_PINYIN_PHRASE_BASE) as out:
        for item in items:
            out.write('{}\n'.format(item))
            out.flush()


def _write_schema():
    print('写方案文件')
    # irime
    copy_dir('../schema/irime', _temp_dir + '/irime')
    copy_files('../schema', _temp_dir + '/irime/SharedSupport', includes='unipy_rime923_[sl].+')
    copy_files('../schema', _temp_dir + '/irime/SharedSupport', includes='rime.lua')
    copy_files('../schema', _temp_dir + '/irime/SharedSupport', includes='stroke_digital.+')
    # trime
    copy_dir('../schema/trime', _temp_dir + '/trime')
    copy_files('../schema', _temp_dir + '/trime', includes='unipy_rime923_[sl].+')
    copy_files('../schema', _temp_dir + '/trime', includes='rime.lua')
    copy_files('../schema', _temp_dir + '/trime', includes='stroke_digital.+')


def _bundle():
    print('打包')
    # irime
    copy_files('../out', _temp_dir + '/irime/SharedSupport', includes='unipy_.+\\.dict.yaml')
    bundle(_temp_dir + '/irime', '../out/rime923-{}-irime'.format(_version))
    # trime
    copy_files('../out', _temp_dir + '/trime', includes='unipy_.+\\.dict.yaml')
    bundle(_temp_dir + '/trime', '../out/rime923-{}-trime'.format(_version))
